from google.appengine.api import users
from google.appengine.ext import webapp

from base_page import BaseHandler
from data import Order
from data import Request

class CreateOrderHandler(BaseHandler):
  # Set authenticating logic in the following two functions.
  def CanEdit(self, user, order):
    if not user:
      return False
    if user.is_sys_admin or user.is_manufacturer_mod:
      return True
    if order == None:
      # TODO: everyone (with profiles) can add a new pledge
      return True
    if pledge.manufacturer_profile.creator.key() == user.key():
      # One can always edit its own order
      return True
    else:
      return False

  def CanApprove(self, user, pledge):
    return user.is_sys_admin or user.is_donor_mod

  def ProcessGet(self):
    self.Setup('create_order.html', required_registered=True)
    order = self.GetEntityByKeyName('oid')
    # Check priviledges
    if self.CanEdit(self.user, order):
      self.template_values['can_edit'] = '1'
    else:
      # require at least editing priviledge to view this page
      self.RedirectLogin()
    if self.CanApprove(self.user, order):
      self.template_values['can_approve'] = '1'
    else:
      self.template_values['can_approve'] = '0'

    # list the user's profiles
    profiles = list(self.user.manufacturerprofile_set)
    if len(profiles) == 0:
      #TODO: alert this error
      self.RedirectAndRaise('/')
    self.template_values['profiles'] = profiles

    if order != None:  # edit an existing order
      self.template_values['order'] = order
      self.template_values['post_action'] = 'Action.edit'
    else:  # add a new order to a request
      request = self.GetEntityByKeyName('qid')
      if request == None:  # error
        self.RedirectAndRaise('/')
      self.template_values['req'] = request
      self.template_values['post_action'] = 'Action.add'
    self.Render()

  def ProcessPost(self):
    self.Setup('create_order.html')
    if self.post_action == 'Action.add':
      self.HandleAdd()
    elif self.post_action == 'Action.edit':
      self.HandleEdit()
    elif self.post_action == 'Action.delete':
      self.HandleDelete()
    elif self.post_action == 'Action.approve':
      self.HandleApprove()
    else:  # default handler
      self.JsonErrorReturn('Unknown action.')

  # Fill the request data from the form input
  def PopulateOrder(self, order):
    order.description = self.request.get('description')
    order.manufacturer_profile = self.GetEntityOrShowError('manufacturer_profile')

  def HandleAdd(self):
    if not self.CanEdit(self.user, None):
      # TODO: more friendly alert
      self.RedirectLogin()

    request = self.GetEntityByKeyName('qid')
    if request == None:
      self.RedirectAndRaise('/')
    order = Order()
    #TODO: manufacturer_profile
    order.request = request
    self.PopulateOrder(order)
    order.put()
    # done
    self.RedirectAndRaise('/viewrequest?qid=%s' % request.key())

  def HandleEdit(self):
    order = self.GetEntityByKeyName('oid')
    if order == None:
      # TODO: more friendly alert
      self.RedirectAndRaise('/')
    if not self.CanEdit(self.user, order):
      # TODO: more friendly alert
      self.RedirectLogin()

    self.PopulateOrder(order)
    order.put()
    self.RedirectAndRaise('viewrequest?qid=%s' % str(order.request.key()))

  def HandleDelete(self):
    order = self.GetEntityByKeyName('oid')
    if order == None:
      # TODO: more friendly alert
      self.RedirectAndRaise('/')

    if not self.CanEdit(self.user, order):
      # TODO: more friendly alert
      self.RedirectLogin()

    # Save the request key before deleting
    qid = order.request.key()
    # TODO: related changes
    order.delete()
    self.RedirectAndRaise('viewrequest?qid=%s' % qid)

  def HandleApprove(self):
    order = self.GetEntityByKeyName('oid')
    if order == None:
      self.JsonErrorReturn('Order does not exist.')

    # Authenticate
    if not self.CanApprove(self.user, order):
      self.JsonErrorReturn('Please login as admin or moderator.')

    new_state = self.request.get('state')
    order.state = int(new_state)
    order.put()

    repsonse = {}
    repsonse['status'] = 'OK'
    repsonse['state'] = new_state
    self.JsonReturn(repsonse)



